package com.example.birdfriends.utils.export;

import com.example.birdfriends.pojo.export.constant.DataExportTypeConstant;
import com.example.birdfriends.pojo.export.vo.DataExportVo;
import com.example.birdfriends.service.DataExportReadService;
import com.example.birdfriends.service.DataExportWriteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.List;

@Component
public class DataExportScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(DataExportScheduleTask.class);
    @Autowired
    private DataExportReadService dataExportReadService = null;
    @Autowired
    private DataExportWriteService dataExportWriteService = null;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${export.file-path}")
    private String filePath;

    @Scheduled(cron = "${scheduled.export-data}")
    public void scheduledTaskByConfig(HttpSession session){
        logger.info("------数据导出任务开始------");
        try{
            List<DataExportVo> dataExportVoList = dataExportReadService.queryDataExportListByExportStat(DataExportTypeConstant.RUN_EXPORT.getValue());
            if(!dataExportVoList.isEmpty()){
                for(DataExportVo dataExportVo: dataExportVoList){
                    // 开始导出job
                    DataExportExcelJob dataExportExcelJob = new DataExportExcelJob(dataExportReadService, dataExportWriteService, jdbcTemplate, filePath);
                    dataExportExcelJob.executionJob(dataExportVo.getExportId(), session);
                }
            }
        }catch (Exception e){
            logger.error("数据到处任务出错：{}\n", e.getCause(), e);
        }
        logger.info("------数据导出任务结束------");
    }
}
